package io.jenkins.plugins;

import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.*;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.BuildStepMonitor;
import hudson.tasks.Notifier;
import hudson.tasks.Publisher;
import hudson.util.FormValidation;
import io.jenkins.plugins.request.AppchatSendDTO;
import io.jenkins.plugins.request.WxRequest;
import jenkins.model.Jenkins;
import jenkins.tasks.SimpleBuildStep;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;

import javax.annotation.Nonnull;
import javax.servlet.ServletException;
import java.io.IOException;
import java.util.HashMap;

public class WxAlarmBuilder extends Notifier implements SimpleBuildStep {

    private final String corpid;

    private final String corpsecret;

    private final String name;

    private final String chatid;

    @DataBoundConstructor
    public WxAlarmBuilder(String corpid, String corpsecret, String name, String chatid) {
        this.corpid = corpid;
        this.corpsecret = corpsecret;
        this.name = name;
        this.chatid = chatid;
    }

    public String getCorpid() {
        return corpid;
    }

    public String getCorpsecret() {
        return corpsecret;
    }

    public String getName() {
        return name;
    }

    public String getChatid() {
        return chatid;
    }

    @Override
    public void perform(@Nonnull Run<?, ?> run, @Nonnull FilePath filePath, @Nonnull Launcher launcher, @Nonnull TaskListener taskListener) throws IOException {

        //获取构建结果
        Result result = run.getResult();
        String resultStr = result == null ? "" : result.toString();
        int number = run.getNumber();

        // 构建失败或者不稳定
        if (resultStr.equals("FAILURE") || resultStr.equals("UNSTABLE")) {
            AppchatSendDTO dto = new AppchatSendDTO();
            dto.setChatid(chatid);
            dto.setText(new HashMap<String, String>() {{
                this.put("content", "构建失败\n" +
                        "项目名称：" + name + "\n" +
                        "构建编号：" + number + "\n" +
                        "构建日志：" + run.getUrl() + "console");
            }});

            WxRequest.sendText(WxRequest.getAccessToken(corpid, corpsecret), dto);
        }

    }

    @Override
    public BuildStepMonitor getRequiredMonitorService() {
        return BuildStepMonitor.NONE;
    }

    @Extension
    public static final class DescriptorImpl extends BuildStepDescriptor<Publisher> {

        public DescriptorImpl() {
            load();
        }

        public FormValidation doCheckName(@QueryParameter String value) throws IOException, ServletException {
            if (value.length() == 0)
                return FormValidation.error("please set a name");
            return FormValidation.ok();
        }

        public FormValidation doCheckCorpid(@QueryParameter String value) throws IOException, ServletException {
            if (value.length() == 0)
                return FormValidation.error("please set a corpid");
            return FormValidation.ok();
        }

        public FormValidation doCheckCorpsecret(@QueryParameter String value) throws IOException, ServletException {
            if (value.length() == 0)
                return FormValidation.error("please set a corpsecret");
            return FormValidation.ok();
        }

        public FormValidation doCheckChatid(@QueryParameter String value) throws IOException, ServletException {
            if (value.length() == 0)
                return FormValidation.error("please set a chatid");
            return FormValidation.ok();
        }

        public boolean isApplicable(Class<? extends AbstractProject> aClass) {
            return true;
        }

        public String getDisplayName() {
            return "微信配置通知";
        }

        public String getDefaultURL() {
            Jenkins instance = Jenkins.getInstance();
            if (instance.getRootUrl() != null) {
                return instance.getRootUrl();
            } else {
                return "";
            }
        }

        @Override
        public boolean configure(StaplerRequest req, JSONObject formData) throws Descriptor.FormException {
            save();
            return super.configure(req, formData);
        }

    }

}
